#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include "sqlite3.h"
#include "get_ID.h"
#include "get_temp.h"
#include "sqlite_select.h"

float sqlite(char *sqlite_topic,char *ID_select,char *time_select,int discon_signal,int con_signal)
{
        int                     rv=-1;
	char                    ID[12]={};
	int                     del_num=1;
	time_t                  rawtime;
       	struct                  tm *info;
	float                   temp;
	float                   temp_select;
	sqlite3                 *db=NULL;
	char                    *errmsg=NULL;
	int                     cmd=-1;
	char                    sql[1024]={};
	char                    *f_value[128]={};

	struct                  rpi_data_s    rpi_data;
	struct                  rpi_ID_s      rpi_ID;
//建立数据库////////////////////////////////////////////////////
	rv=sqlite3_open(sqlite_topic, &db);
	if(rv!=SQLITE_OK)
	{
	//	log_error("Open db failure:%s\n", sqlite3_errmsg(db));
		printf("Open db failure:%s\n", sqlite3_errmsg(db));
		return -1;
	}
	printf("open db successful!\n");
//	log_info("open db successful!\n");
	
	rv=sqlite3_exec(db, "create table if not exists temp(num INTEGER PRIMARY KEY, ID TEXT , time TEXT, temperature REAL)", NULL, NULL, &errmsg);
	if(rv!=SQLITE_OK)
	{
	//	log_error("Create table failure:%s\n", errmsg);
		printf("Create table failure:%s\n", errmsg);
		return -2;
	}
	printf("create table successful!\n");
//	log_info("create table successful!\n");
	
	while(discon_signal)
	{
		printf("sqlite insert  start...\n");
//		log_info("sqlite insert  start...\n");
	
		time( &rawtime );
		info =localtime( &rawtime );
		
		memset(sql, 0, sizeof(sql));
		sprintf(sql,"insert into temp (ID,time,temperature)values('%s','%s','%f')",rpi_ID.ID, asctime(info), rpi_data.temp);
		rv=sqlite3_exec(db, sql, NULL, NULL, &errmsg);
		if(rv!=SQLITE_OK)
		{
			printf("insert error:%s\n", errmsg);
	//		log_error("insert error:%s\n", errmsg);
			return -1;
		}
		printf("insert ok\n");
//		log_info("insert ok");
		sleep(3);
	}

	if(con_signal=1)
	{
		temp_select=sqlite_select(db,ID_select,time_select);
		if(!temp_select)
		{
			printf("select NULL!\n");
		//	log_info("select NULL!\n");
			con_signal=0;
		}
		
		memset(sql, 0, sizeof(sql));
		sprintf(sql,"delete from temp where num=%d",del_num);
		rv=sqlite3_exec(db, sql, NULL, NULL, &errmsg);
		if(rv!=SQLITE_OK)
		{
			printf("error:%s\n", errmsg);
		//	log_error("error:%s\n", errmsg);
			return -4;
		}
		printf("delete successful!\n");
	//	log_info("delete successful!\n");
		del_num++;
	}
	sqlite3_close(db);
	return temp_select;
}

